package cn.wolfcode.wolfcodemall.controller.admin;

import cn.wolfcode.wolfcodemall.domain.Admin;
import cn.wolfcode.wolfcodemall.service.AdminService;
import cn.wolfcode.wolfcodemall.util.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录相关请求的处理器
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private AdminService adminService;
    //登录页面的请求
    @RequestMapping("/loginPage")
    public String loginPage(){
        //跳转到登录页面
        return "/admin/loginPage";
    }
    //验证码请求
    @RequestMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
        //生成一张验证码图片，发送给浏览器显示
        VerifyCodeUtil.getVerifyCode(request, response);
    }
    //登录请求
    @RequestMapping("/doLogin")
    public String doLogin(String username, String password,
                          String verifycode,
                          HttpServletRequest request,
                          HttpSession session,
                          Model model){
        //调用service登录的方法
        try{
            Admin login = adminService.login(username, password, verifycode, request);
            session.setAttribute("admin",login);
            //登录成功，跳转到分类管理页面请求
            return "redirect:/admin/category";
        }catch(Exception e){
            //获取异常信息
            String errorMsg = e.getMessage();
            // 将异常信息带到页面中显示
            model.addAttribute("errorMsg",errorMsg);
            //登录失败，跳转回到登录页面
            return "/admin/loginPage";
        }
    }
}
